package com.ysd.lis.service.lab.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.mapper.lab.LabRptGroupMapper;
import com.ysd.lis.mapper.lab.LabRptresultImageMapper;
import com.ysd.lis.request.men.UploadImageDto;
import com.ysd.lis.service.lab.LabRptresultImageService;
import com.ysd.util.PropertySlash;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.sql.Timestamp;
import java.util.Base64;
import java.util.List;

/**
 * @author wanghao
 * @create 2024/1/2 0002
 */
@Service
public class LabRptresultImageServiceImpl extends ServiceImpl<LabRptresultImageMapper, LabRptresultImage> implements LabRptresultImageService {

    @Autowired
    LabRptresultImageMapper labRptresultImageMapper;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;

    @Autowired
    LabRptGroupMapper labRptGroupMapper;

    @Value("${picturePath}")
    private String picturePath;

    @Override
    public Result findImagesByMaininfoId(RptResultDto rptResultDto) {
        if (StringUtils.isBlank(rptResultDto.getRptGroup()) || StringUtils.isBlank(rptResultDto.getSampleNo()) || StringUtils.isBlank(rptResultDto.getSampleda())) {
            return Result.fail("参数不能为空");
        }
        Timestamp startTime = Timestamp.valueOf(rptResultDto.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(rptResultDto.getSampleda().substring(0, 10) + " 23:59:59");

        LambdaQueryWrapper<LabRptresultImage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptresultImage::getDelFlag, 0);

        // 添加一组条件，当RptGroup, SampleNo, Sampleda 都满足时
        queryWrapper.and(wrapper -> wrapper
                .eq(LabRptresultImage::getRptGroup, rptResultDto.getRptGroup())
                .eq(LabRptresultImage::getSampleNo, rptResultDto.getSampleNo())
                .ge(LabRptresultImage::getSampleda, startTime)
                .le(LabRptresultImage::getSampleda, endTime));

        // 或者添加另一个条件，仅根据MaininfoId查询
        //queryWrapper.or().eq(LabRptresultImage::getMaininfoId, rptResultDto.getMaininfoId());
        queryWrapper.orderByAsc(LabRptresultImage::getSeq);
        List<LabRptresultImage> labRptresultImages = labRptresultImageMapper.selectList(queryWrapper);

        return Result.succ(1, "查询结果成功", labRptresultImages);
    }

    @Override
    public Result saveOrUpdateImages(LabRptresultImage labRptresultImage) {

        boolean b = this.saveOrUpdate(labRptresultImage);
        if (b) {
            return Result.succ(1, "成功", null);
        } else {
            return Result.fail(400, "失败", "");
        }
    }

    @Override
    public Result batchDeleteImages(List<String> imagesIds) {

        if (CollectionUtils.isEmpty(imagesIds)) {
            return Result.fail("请选择一条检验结果！");
        } else {
            boolean b = this.removeByIds(imagesIds);
            if (b) {
                return Result.succ(1, "删除成功！", null);
            } else {
                return Result.fail("删除失败！");
            }
        }
    }

    @Override
    public Result uploadImageFiles(UploadImageDto uploadImageDto) {
      /*  LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getRptGroup, uploadImageDto.getRptGroup());
        queryWrapper.eq(LabMaininfo::getSampleNo, uploadImageDto.getSampleNo());
        Timestamp startTime = Timestamp.valueOf(uploadImageDto.getSampleda() + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(uploadImageDto.getSampleda() + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

            LabMaininfo labMaininfo = labMaininfos.get(0);*/

        //将base64字符串转为字节
        if (StringUtils.isBlank(uploadImageDto.getOrgId())) {
            LambdaQueryWrapper<LabRptGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabRptGroup::getRptGroup, uploadImageDto.getRptGroup());
            lambdaQueryWrapper.eq(LabRptGroup::getDelFlag, 0);
            LabRptGroup labRptGroup = labRptGroupMapper.selectList(lambdaQueryWrapper).get(0);
            uploadImageDto.setOrgId(StringUtils.isBlank(labRptGroup.getOrgId()) ? "" : labRptGroup.getOrgId());
        }

        String base64Str = uploadImageDto.getFileData().replaceAll("data:image/jpeg;base64,", "");
        byte[] buffer = Base64.getDecoder().decode(base64Str);
        String folder = picturePath + "\\" + uploadImageDto.getSampleda().substring(0, 10) + "\\" + uploadImageDto.getInstrCode() + PropertySlash.getSlash();
        if (!FileUtil.exist(folder)) {
            FileUtil.mkdir(folder);
        }
        String fileName = uploadImageDto.getSampleda() + uploadImageDto.getRptGroup() + uploadImageDto.getSampleNo() + uploadImageDto.getInstrCode() + uploadImageDto.getFileName();
        String path = folder + fileName;
        File file1 = FileUtil.writeBytes(buffer, path);
        if (file1.length() < 0) {
            return Result.fail("文件上传失败");
        }
        LabRptresultImage labRptresultImage = new LabRptresultImage();
        labRptresultImage.setImageName(uploadImageDto.getFileName());
        labRptresultImage.setRptGroup(uploadImageDto.getRptGroup());

        LambdaQueryWrapper<LabMaininfo> maininfoWrapper = new LambdaQueryWrapper<>();
        maininfoWrapper.eq(LabMaininfo::getDelFlag, 0);
        maininfoWrapper.and(item->item.eq(LabMaininfo::getSampleNo, uploadImageDto.getSampleNo()).or().eq(LabMaininfo::getReqNo, uploadImageDto.getSampleNo()));
        Timestamp startTime1 = Timestamp.valueOf(uploadImageDto.getSampleda() + " 00:00:00");
        Timestamp endTime1 = Timestamp.valueOf(uploadImageDto.getSampleda() + " 23:59:59");
        maininfoWrapper.ge(LabMaininfo::getSampleda, startTime1);
        maininfoWrapper.le(LabMaininfo::getSampleda, endTime1);
        maininfoWrapper.eq(LabMaininfo::getRptGroup, uploadImageDto.getRptGroup());
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(maininfoWrapper);
        if (CollectionUtils.isNotEmpty(labMaininfos)) {
            labRptresultImage.setSampleNo(labMaininfos.get(0).getSampleNo());
        }else {
            labRptresultImage.setSampleNo(uploadImageDto.getSampleNo());
        }

        labRptresultImage.setSampleda(Timestamp.valueOf(uploadImageDto.getSampleda().substring(0, 10) + " 00:00:00"));
        labRptresultImage.setImageUrl("/image/" + uploadImageDto.getSampleda().substring(0, 10) + "/" + uploadImageDto.getInstrCode() + "/" + fileName);
        labRptresultImage.setImageExt(uploadImageDto.getFileType());
        //labRptresultImage.setMaininfoId(labMaininfo.getId());
        labRptresultImage.setSeq(uploadImageDto.getSeq());
        labRptresultImage.setOrgId(uploadImageDto.getOrgId());
        labRptresultImage.setCreateTime(new Timestamp(System.currentTimeMillis()));
        int insert = labRptresultImageMapper.insert(labRptresultImage);
        if (insert > 0) {
            return Result.succ(1, "上传成功", "");
        } else {
            return Result.fail(400, "上传失败", "");
        }

    }
}
